<template>
  <el-dialog
    title="编辑文章"
    :visible.sync="visible"
    width="1100px"
    top="5vh"
    :before-close="
      () => {
        $emit('close');
      }
    "
    @close="editorDestroy"
  >
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input :maxlength="50" v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="classify">
        <el-select v-model="form.classify" placeholder="请选择">
          <el-option
            v-for="item in classifyList"
            :key="item.id"
            :label="item.dynamic_name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联商品" prop="goods">
        <el-autocomplete
          style="width:300px;"
          v-model="form.goodsName"
          :fetch-suggestions="querySearchAsync"
          value-key="name"
          value="id"
          placeholder="请输入商品名称"
          @select="handleSelect"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="缩略图" prop="avatar">
        <el-upload
          action="/#"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="imgRemove"
          :file-list="form.avatar"
          :limit="1"
          :http-request="imgUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="详情">
        <div id="toolbar1" style="border: 1px solid #dfdfdf;"></div>
        <div
          id="editor1"
          style="height:250px; border: 1px solid #dfdfdf;"
        ></div>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import E from "wangeditor";
let editor = new E("#toolbar1", "#editor1");
import { fileUpload } from "@/api/file";
import {
  addArticle,
  getArticleDetail,
  getArticleClassifyList
} from "@/api/dynamic-mng";
import { searchGoodsList, getGoodDetailOne } from "@/api/good-mng";
export default {
  props: ["visible", "id"],
  data() {
    return {
      form: {
        title: null,
        goods: null,
        avatar: [],
        goodsName: null,
        classify: null
      },
      classifyList: [],
      rules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        classify: [
          { required: true, message: "请选择文章分类", trigger: "blur" }
        ],
        goods: [{ required: true, message: "请关联有效商品", trigger: "blur" }],
        avatar: [{ required: true, message: "请上传缩略图", trigger: "blur" }]
      },
      goodDetailOne: {},
      dialogVisible: false,
      dialogImageUrl: ""
    };
  },
  watch: {
    visible: function(val) {
      if (val) {
        this.editorInit();
        if (this.id) {
          getArticleDetail({ id: this.id }).then(res => {
            if (res.code === 200) {
              this.form.title = res.data.describe;
              this.form.avatar.push({ name: "", url: res.data.links[0] });
              editor.txt.html(res.data.content);
              this.form.classify = res.data.mic_classify_id;
            }
          });
        }
      } else {
        this.$refs.form.resetFields();
      }
    }
  },
  methods: {
    querySearchAsync(string, cb) {
      searchGoodsList({
        page: 1,
        condition: string ? string : null
      }).then(res => {
        if (res.code === 200) {
          if (res.data.length === 0) this.form.goods = null;
          cb(res.data);
        }
      });
    },
    handleSelect(item) {
      console.log(item);
      this.form.goods = item.id;
    },
    submit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let data = {
            id: this.id ? this.id : undefined,
            describe: this.form.title,
            links: [this.form.avatar[0].url],
            content: editor.txt.html(),
            mic_classify_id: this.form.classify,
            commodity_id: this.form.goods
          };
          addArticle(data).then(res => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "保存成功!"
              });
              this.$emit("close");
            }
          });
        } else {
          return false;
        }
      });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    imgUpload(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      fileUpload(formData).then(res => {
        if (res.code === 200) {
          this.form.avatar.push({
            name: "",
            url: res.data.file,
            uid: file.file.uid
          });
        }
      });
    },
    imgRemove(file, fileList) {
      this.form.avatar.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form.avatar.splice(index, 1);
          return;
        }
      });
    },
    getGoodDetail() {
      getGoodDetail({ id: this.currentId }).then(res => {
        if (res.code === 200) {
          editor.txt.html(res.data.introduce);
          this.is_putaway = res.data.is_putaway;
        }
      });
    },
    editorInit() {
      this.$nextTick(() => {
        editor.customConfig.zIndex = 100;
        editor.customConfig.customUploadImg = function(files, insert) {
          console.log(files.length);
          for (let i = 0; i < files.length; i++) {
            let formData = new FormData();
            formData.append("file", files[i]);
            fileUpload(formData).then(res => {
              if (res.code === 200) {
                insert(res.data.file);
              }
            });
          }
        };
        editor.create();
      });
    },
    editorDestroy() {
      document.getElementById("editor1").innerHTML = "";
    }
  },
  created() {
    getArticleClassifyList().then(res => {
      if (res.code === 200) {
        this.classifyList = res.data;
      }
    });
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
.bottom-bar {
  text-align: center;
  button {
    width: 180px;
  }
}
</style>
